package com.kgc.springboot_shiro.controller;

import com.kgc.springboot_shiro.entity.User;
import com.kgc.springboot_shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Set;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(User user)
    {
        System.out.println(user.getRememberMe());
        System.out.println("username = " + user.getUsername());
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());

        Subject subject = SecurityUtils.getSubject();
        try {
            if (user.getRememberMe()!=null)
            {
                token.setRememberMe(true);
            }
            subject.login(token);
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println(" 用户名错误 ");
        }catch (IncorrectCredentialsException e)
        {
            e.printStackTrace();
            System.out.println(" 密码错误");
        }
        return "redirect:/login.jsp";
    }

    @RequestMapping("/logout")
    public String logout()
    {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(User user)
    {
        try {
            userService.redister(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }

    @RequiresRoles("super")
    @RequestMapping("/delete")
    public String delete(Integer id)
    {

        System.out.println("id = " + id);
        return "redirect:/index.jsp";
    }

    @RequiresRoles({"super","admin"})
    @RequestMapping("/update")
    public String update(Integer id)
    {

        System.out.println("id = " + id);
        return "redirect:/index.jsp";
    }
}
